﻿using System;
using System.Threading.Tasks;
using VirtualDeveloper.CodeTransformation;
using VirtualDeveloper.Filters;

namespace VirtualDeveloper
{
    internal class WorkingDeveloper : IWorkingDeveloper
    {
        private readonly string directory;
        private readonly string filter;


        private readonly IFileAdapter fileAdapter;

        public WorkingDeveloper(string directory, string filter = "*.cs")
            : this(directory, filter, new FileAdapter())
        {
        }

        internal WorkingDeveloper(string directory, string filter, IFileAdapter fileAdapter)
        {
            this.directory = directory;
            this.fileAdapter = fileAdapter;
            this.filter = filter;
        }

        private static string[] Words()
        {
            return
                @"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
                    .Split(new[] { Environment.NewLine, " " }, StringSplitOptions.RemoveEmptyEntries);
        }

        public void LittleChanges()
        {
            ChangeFiles(6, () => new Developer(new RandomEnumerable<ILineTransformer>(
                new ReplaceCode(),
                new DuplicateLine(),
                new DoNothing(),
                new DoNothing(),
                new DoNothing(),
                new DoNothing(),
                new DoNothing(),
                new DoNothing()
                )));
        }

        public void StandardChanges()
        {
            ChangeFiles(2, () => new Developer(new RandomEnumerable<ILineTransformer>(new ReplaceCode(), new AddCodeToBeginning(), new DoNothing(), new ReplaceCode(), new AddCodeToEndAndBeginnning(), new DoNothing(), new DoNothing(), new DoNothing())));
        }

        public void BigChanges()
        {
            ChangeFiles(1, () => new Developer(new RandomEnumerable<ILineTransformer>(new ReplaceCode(), new AddCodeToBeginning(), new AddCodeToEnd(), new DuplicateLine())));
        }

        private void ChangeFiles(int everyLineCount, Func<Developer> developerFactory)
        {
            Parallel.ForEach(new LineSkipper<string>(fileAdapter.GetFiles(directory, filter), everyLineCount),
                file => fileAdapter.SaveToFile(file, developerFactory().Code(fileAdapter.ReadAllText(file), Words())));
        }
    }
}
